import 'package:cloud_medicine/components/above_loading.dart';
import 'package:cloud_medicine/components/close_circle.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:cloud_medicine/pages/image_show.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';

class UserVerifyPage extends StatefulWidget {
  @override
  _UserVerifyPageState createState() => _UserVerifyPageState();
}

class _UserVerifyPageState extends State<UserVerifyPage> {
  TextEditingController controller = TextEditingController();
  List<String> _imageList = []; // 从ImagePicker里面选中的图片
  final picker = ImagePicker();
  DateTime lastPopTime; //上次点击时间

// 生成gridView的网格视图图片
  List<Widget> getWidgetList() {
    List<Widget> filesListShow = [];
    for (int j = 0; j < _imageList.length; j++) {
      filesListShow.add(getFileItemContainer(_imageList[j], j));
    }
    // 增加最后的一个添加图片的图标
    filesListShow.add(GestureDetector(
      onTap: pickImage,
      child: Container(
        width: 50,
        height: 50,
        decoration: BoxDecoration(
            border: Border.all(width: 1, color: Colors.lightBlueAccent)),
        child: Icon(Icons.add, color: Colors.lightBlueAccent),
      ),
    ));
    return filesListShow;
  }

// 生成每一张图片的样式
  Widget getItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: FadeInImage.assetNetwork(
                placeholder: 'images/loading.gif', // 占位图
                image: file,
              ),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

// 生成每一张图片的样式（路径来源于文件）
  Widget getFileItemContainer(String file, int index) {
    return GestureDetector(
      child: Container(
        child: Stack(
          children: <Widget>[
            Align(
              child: Image.network(file),
              alignment: Alignment.center,
            ),
            Align(
              child: CloseCircle(index: index, callback: deleteImage),
              alignment: Alignment(0.9, -0.9),
            )
          ],
        ),
        color: Colors.grey[100],
      ),
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => ImageShow(
                  url: file,
                  isFile: false,
                )));
      },
    );
  }

// 删除图片
  void deleteImage(int index) {
    setState(() {
      _imageList.removeAt(index);
    });
  }

// 在底部显示图片选取方式
  pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: <Widget>[_item('拍照', true), _item('从相册选择', false)],
              ),
            ));
  }

// 在底部生成每一项部件
  _item(String title, bool isTakePhoto) {
    return GestureDetector(
      child: ListTile(
        leading: Icon(isTakePhoto ? Icons.camera_alt : Icons.photo_library),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

// 拍照或从图库中选取图片
  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    final pickedFile = await picker.getImage(
        source: isTakePhoto ? ImageSource.camera : ImageSource.gallery);

    showDialog(
        context: context,
        builder: (context) {
          return new AboveLoading(
            content: '上传中',
          );
        });
    await upLoadImage(File(pickedFile.path), (imageUrl) {
      setState(() {
        _imageList.add(imageUrl);
      });
      Navigator.pop(context);
    });
  }

// 判断loading并且在loading为false时渲染主要视图
  Widget _childLayout() {
    return ListView(
      children: <Widget>[
        Container(
          padding: EdgeInsets.all(8),
          child: TextField(
            controller: controller,
            keyboardType: TextInputType.multiline,
            decoration: InputDecoration(
              hintText: '输入验证信息',
              border: InputBorder.none,
            ),
            minLines: 3,
            maxLines: 8,
          ),
        ),
        SizedBox(height: 20),
        Container(
          padding: EdgeInsets.all(8),
          child: GridView.count(
            physics: new NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            crossAxisSpacing: 10.0,
            mainAxisSpacing: 10.0,
            crossAxisCount: 3,
            childAspectRatio: 1.0,
            children: getWidgetList(),
          ),
        )
      ],
    );
  }

// 回到医生列表页面
  _entryDoctorListPage() {
    Navigator.pop(context);
  }

  // 提交数据
  _submit() {
    submitUserVerifyList_api({
      'content': controller.text,
      'files': _imageList,
    });
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          if (lastPopTime == null ||
              DateTime.now().difference(lastPopTime) > Duration(seconds: 1)) {
            //两次点击间隔超过1秒则重新计时
            lastPopTime = DateTime.now();
            openAlertDialog(
                context, _entryDoctorListPage, '确认退出编辑，一旦退出，一切将不予保存');
            return new Future.value(false);
          }
          return new Future.value(true);
        },
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('填写用户验证信息'),
            actions: <Widget>[
              GestureDetector(
                  onTap: _submit,
                  child: Flex(
                    direction: Axis.vertical,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(right: 10),
                        child: Text('提交', style: TextStyle(fontSize: 18)),
                      )
                    ],
                  ))
            ],
          ),
          body: _childLayout(),
        ));
  }
}
